// 全局状态
let currentUser = null;
let accessToken = localStorage.getItem('access_token');
let cart = [];
let products = [];
let filteredProducts = [];
let loadedProducts = 0;
const productsPerLoad = 6;
let currentCategory = 'all';
let currentSearch = '';

// DOM元素
const productsContainer = document.getElementById('products-container');
const loadMoreBtn = document.getElementById('loadMoreBtn');
const loadingIndicator = document.getElementById('loadingIndicator');
const noMoreProducts = document.getElementById('noMoreProducts');
const noProductsFound = document.getElementById('noProductsFound');
const resetSearchBtn = document.getElementById('resetSearchBtn');
const categoryButtons = document.querySelectorAll('.category-btn');
const toast = document.getElementById('toast');
const toastMessage = document.getElementById('toastMessage');
const cartBtn = document.getElementById('cartBtn');
const cartSidebar = document.getElementById('cartSidebar');
const closeCartBtn = document.getElementById('closeCartBtn');
const startShoppingBtn = document.getElementById('startShoppingBtn');
const cartItems = document.getElementById('cartItems');
const cartCount = document.getElementById('cartCount');
const emptyCart = document.getElementById('emptyCart');
const cartTotal = document.getElementById('cartTotal');
const checkoutBtn = document.getElementById('checkoutBtn');
const overlay = document.getElementById('overlay');
const mobileMenuBtn = document.getElementById('mobileMenuBtn');
const mobileMenu = document.getElementById('mobileMenu');
const searchInput = document.getElementById('searchInput');
const searchBtn = document.getElementById('searchBtn');
const mobileSearchInput = document.getElementById('mobileSearchInput');
const mobileSearchBtn = document.getElementById('mobileSearchBtn');
const searchResultHint = document.getElementById('searchResultHint');
const categoryResultHint = document.getElementById('categoryResultHint');
const categoryName = document.getElementById('categoryName');
const categoryCount = document.getElementById('categoryCount');
const searchKeyword = document.getElementById('searchKeyword');
const searchCount = document.getElementById('searchCount');
const userInfo = document.getElementById('user-info');
const logoutBtn = document.getElementById('logoutBtn');
const quickViewModal = document.getElementById('quickViewModal');
const closeQuickViewBtn = document.getElementById('closeQuickViewBtn');
const quickViewImage = document.getElementById('quickViewImage');
const quickViewTitle = document.getElementById('quickViewTitle');
const quickViewCategory = document.getElementById('quickViewCategory');
const quickViewRating = document.getElementById('quickViewRating');
const quickViewReviews = document.getElementById('quickViewReviews');
const quickViewPrice = document.getElementById('quickViewPrice');
const quickViewDescription = document.getElementById('quickViewDescription');
const quickViewQty = document.getElementById('quickViewQty');
const quickViewDecreaseQty = document.getElementById('quickViewDecreaseQty');
const quickViewIncreaseQty = document.getElementById('quickViewIncreaseQty');
const quickViewAddToCart = document.getElementById('quickViewAddToCart');
const quickViewProductLink = document.getElementById('quickViewProductLink');
let currentQuickViewProductId = null;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    setupEventListeners();
    checkAuth().then(() => {
        loadProducts();
        loadCart();
    });
});

// 设置事件监听器
function setupEventListeners() {
    // 移动端菜单
    if (mobileMenuBtn) { // 先检查元素是否存在
        mobileMenuBtn.addEventListener('click', toggleMobileMenu);
    }
    // 购物车侧边栏 - 优化元素不存在的情况
    if (cartBtn) { // 仅当元素存在时才绑定事件
        cartBtn.addEventListener('click', openCartSidebar);
    }
    overlay.addEventListener('click', closeCartSidebar);
    
    // 加载更多按钮
    if(loadMoreBtn) {
        loadMoreBtn.addEventListener('click', loadMoreProducts);
    }
    if(resetSearchBtn) {
        // 重置搜索
        resetSearchBtn.addEventListener('click', () => {
            currentSearch = '';
            searchInput.value = '';
            mobileSearchInput.value = '';
            categoryButtons.forEach(btn => {
                if (btn.dataset.category === 'all') btn.click();
            });
        });
    }

    // 分类按钮点击事件
    categoryButtons.forEach(button => {
        button.addEventListener('click', () => {
            currentCategory = button.dataset.category;
            currentSearch = '';
            searchInput.value = '';
            mobileSearchInput.value = '';
            
            // 更新按钮样式
            categoryButtons.forEach(btn => btn.classList.remove('category-active'));
            button.classList.add('category-active');
            
            // 重置加载状态并重新加载商品
            resetProductDisplay();
            updateResultHints();
            renderVisibleProducts();
        });
    });
    
    // 搜索功能
    if(searchBtn) {
        searchBtn.addEventListener('click', performSearch);
        mobileSearchBtn.addEventListener('click', performSearch);
        searchInput.addEventListener('keypress', (e) => e.key === 'Enter' && performSearch());
        mobileSearchInput.addEventListener('keypress', (e) => e.key === 'Enter' && performSearch());
    }

    // 登出按钮
    logoutBtn.addEventListener('click', logout);
    // 购物车侧边栏关闭按钮
    if(startShoppingBtn) {
        startShoppingBtn.addEventListener('click', closeCartSidebar);
        closeCartBtn.addEventListener('click', closeCartSidebar);

        // 快速查看模态框
        closeQuickViewBtn.addEventListener('click', closeQuickViewModal);
        quickViewModal.addEventListener('click', (e) => {
            if (e.target === quickViewModal) closeQuickViewModal();
        });
        
        // 快速查看数量调整
        quickViewDecreaseQty.addEventListener('click', () => {
            const qty = parseInt(quickViewQty.value);
            if (qty > 1) quickViewQty.value = qty - 1;
        });
        
        quickViewIncreaseQty.addEventListener('click', () => {
            const qty = parseInt(quickViewQty.value);
            quickViewQty.value = qty + 1;
        });
        
        quickViewQty.addEventListener('change', () => {
            let qty = parseInt(quickViewQty.value);
            quickViewQty.value = isNaN(qty) || qty < 1 ? 1 : qty;
        });
        
        // 快速查看加入购物车
        quickViewAddToCart.addEventListener('click', () => {
            if (currentQuickViewProductId) {
                addToCart(currentQuickViewProductId, parseInt(quickViewQty.value));
                closeQuickViewModal();
            }
        }); 

        // 结算按钮
        checkoutBtn.addEventListener('click', () => {
            if (cart.length === 0) return;
            if (!accessToken) {
                showToast('请先登录', 'warning');
                setTimeout(() => window.location.href = 'login.html', 1000);
                return;
            }
            showToast('跳转到结算页面', 'info');
            // 实际项目中这里会跳转到结算页面
        });                
    }    
    // 滚动时导航栏效果
    window.addEventListener('scroll', () => {
        const navbar = document.getElementById('navbar');
        if (window.scrollY > 50) {
            navbar.classList.add('shadow-md');
            navbar.classList.remove('shadow-sm');
        } else {
            navbar.classList.remove('shadow-md');
            navbar.classList.add('shadow-sm');
        }
    });
}

// 加载所有商品
async function loadProducts() {
    try {
        const response = await fetch('http://192.168.10.124:8000/products/');
        if (!response.ok) throw new Error('Failed to load products');
        products = await response.json();
        resetProductDisplay();
        updateResultHints();
        renderVisibleProducts();
    } catch (error) {
        console.error('Error loading products:', error);
        showToast('加载商品失败，请稍后重试', 'error');
        productsContainer.innerHTML = `
            <div class="col-span-full text-center py-12">
                <p class="text-gray-500">加载商品失败，请刷新页面重试</p>
                <button onclick="window.location.reload()" class="mt-4 btn-primary">
                    刷新页面
                </button>
            </div>
        `;
    }
}

// 从服务器加载购物车
async function loadCart() {
    if (!accessToken) return;
    
    try {
        const response = await fetch('http://192.168.10.124:8000/cart/', {
            headers: { 'Authorization': `Bearer ${accessToken}` }
        });
        
        if (response.ok) {
            const cartData = await response.json();
            cart = cartData.items || [];
            updateCartUI();
        }
    } catch (error) {
        console.error('Error loading cart:', error);
    }
}

// 重置商品显示
function resetProductDisplay() {
    loadedProducts = 0;
    productsContainer.innerHTML = '';
    filteredProducts = filterProducts(products);
    toggleLoadMoreButton();
}

// 过滤商品
function filterProducts(productsList) {
    return productsList.filter(product => {
        // 分类过滤
        const categoryMatch = currentCategory === 'all' || product.category === currentCategory;
        // 搜索过滤
        const searchMatch = !currentSearch || 
            product.name.toLowerCase().includes(currentSearch.toLowerCase()) ||
            product.description.toLowerCase().includes(currentSearch.toLowerCase());
        return categoryMatch && searchMatch;
    });
}

// 更新结果提示
function updateResultHints() {
    if (currentSearch) {
        searchResultHint.classList.remove('hidden');
        categoryResultHint.classList.add('hidden');
        searchKeyword.textContent = currentSearch;
        searchCount.textContent = filteredProducts.length;
    } else {
        searchResultHint.classList.add('hidden');
        categoryResultHint.classList.remove('hidden');
        
        // 设置分类名称
        const categoryMap = {
            'all': '全部商品',
            '电子产品': '电子产品',
            '服装鞋帽': '服装鞋帽',
            '家居用品': '家居用品'
        };
        categoryName.textContent = categoryMap[currentCategory] || '全部商品';
        categoryCount.textContent = filteredProducts.length;
    }
    
    // 显示或隐藏"没有找到商品"提示
    if (filteredProducts.length === 0) {
        noProductsFound.classList.remove('hidden');
        loadMoreBtn.classList.add('hidden');
        noMoreProducts.classList.add('hidden');
    } else {
        noProductsFound.classList.add('hidden');
    }
}

// 渲染可见商品
function renderVisibleProducts() {
    if (filteredProducts.length === 0) return;
    
    const productsToLoad = filteredProducts.slice(loadedProducts, loadedProducts + productsPerLoad);
    renderProducts(productsToLoad);
    loadedProducts += productsToLoad.length;
    toggleLoadMoreButton();
}

// 渲染商品列表
function renderProducts(productsList) {
    productsList.forEach(product => {
        const productCard = document.createElement('div');
        productCard.className = 'bg-white rounded-lg shadow-sm hover:shadow-md transition-shadow overflow-hidden group';
        productCard.innerHTML = `
            <div class="relative overflow-hidden">
                <img src="${product.image_url}" alt="${product.name}" class="w-full h-48 object-cover transition-transform duration-500 group-hover:scale-105">
                <button class="quick-view-btn absolute top-2 right-2 bg-white/80 p-2 rounded-full text-gray-600 hover:text-primary transition-colors" data-id="${product.id}">
                    <i class="fa fa-eye"></i>
                </button>
            </div>
            <div class="p-4">
                <div class="text-sm text-gray-500 mb-1">${product.category}</div>
                <h3 class="font-medium mb-2 line-clamp-1">${product.name}</h3>
                <div class="flex items-center mb-2">
                    <div class="text-yellow-400 text-xs">${generateRatingStars(product.rating)}</div>
                    <span class="text-xs text-gray-500 ml-1">(${product.reviews}条评价)</span>
                </div>
                <div class="flex justify-between items-center">
                    <span class="font-bold text-primary">¥${product.price.toFixed(2)}</span>
                    <button class="add-to-cart-btn p-2 bg-primary/10 text-primary rounded-full hover:bg-primary hover:text-white transition-colors" data-id="${product.id}">
                        <i class="fa fa-shopping-cart"></i>
                    </button>
                </div>
            </div>
        `;
        productsContainer.appendChild(productCard);
    });

    // 为新添加的商品绑定事件
    document.querySelectorAll('.add-to-cart-btn:not([data-bound])').forEach(btn => {
        btn.setAttribute('data-bound', 'true');
        btn.addEventListener('click', () => {
            const productId = parseInt(btn.dataset.id);
            addToCart(productId, 1);
        });
    });

    // 为快速查看按钮绑定事件
    document.querySelectorAll('.quick-view-btn:not([data-bound])').forEach(btn => {
        btn.setAttribute('data-bound', 'true');
        btn.addEventListener('click', () => {
            const productId = parseInt(btn.dataset.id);
            openQuickViewModal(productId);
        });
    });
}

// 生成星级评分HTML
function generateRatingStars(rating) {
    let stars = '';
    const fullStars = Math.floor(rating);
    const hasHalfStar = rating % 1 >= 0.5;
    
    for (let i = 0; i < fullStars; i++) {
        stars += '<i class="fa fa-star"></i>';
    }
    
    if (hasHalfStar) {
        stars += '<i class="fa fa-star-half-o"></i>';
    }
    
    const emptyStars = 5 - fullStars - (hasHalfStar ? 1 : 0);
    for (let i = 0; i < emptyStars; i++) {
        stars += '<i class="fa fa-star-o"></i>';
    }
    
    return stars;
}

// 加载更多商品
function loadMoreProducts() {
    if (loadedProducts >= filteredProducts.length) {
        loadMoreBtn.classList.add('hidden');
        return;
    }
    loadMoreBtn.classList.add('hidden');
    loadingIndicator.classList.remove('hidden');
    // 模拟加载延迟
    setTimeout(() => {
        renderVisibleProducts();
        loadingIndicator.classList.add('hidden');
        loadMoreBtn.classList.remove('hidden');
    }, 800);
}

// 切换加载更多按钮显示状态
function toggleLoadMoreButton() {
    console.warn('已加载:', loadedProducts, '总商品数:', filteredProducts.length); // 新增日志
    if (loadedProducts >= filteredProducts.length) {
        loadMoreBtn.classList.add('hidden');  // 隐藏加载更多按钮
        noMoreProducts.classList.remove('hidden');  // 显示"没有更多商品"提示
    } else {
        loadMoreBtn.classList.remove('hidden');  // 显示加载更多按钮
        noMoreProducts.classList.add('hidden');  // 隐藏"没有更多商品"提示
    }
}

// 执行搜索
function performSearch() {
    currentSearch = searchInput.value.trim() || mobileSearchInput.value.trim();
    currentCategory = 'all';
    
    // 更新分类按钮样式
    categoryButtons.forEach(btn => {
        if (btn.dataset.category === 'all') {
            btn.classList.add('category-active');
        } else {
            btn.classList.remove('category-active');
        }
    });
    
    // 重置加载状态并重新加载商品
    resetProductDisplay();
    updateResultHints();
    renderVisibleProducts();
}

// 显示提示消息
function showToast(message, type = 'success') {
    toastMessage.textContent = message;
    
    // 根据类型设置不同图标
    const icon = toast.querySelector('i');
    if (type === 'warning') {
        icon.className = 'fa fa-exclamation-circle text-yellow-400 mr-2';
    } else if (type === 'error') {
        icon.className = 'fa fa-times-circle text-red-500 mr-2';
    } else if (type === 'info') {
        icon.className = 'fa fa-info-circle text-blue-400 mr-2';
    } else {
        icon.className = 'fa fa-check-circle text-secondary mr-2';
    }
    
    // 显示提示
    toast.classList.remove('translate-y-20', 'opacity-0');
    toast.classList.add('translate-y-0', 'opacity-100');
    
    // 3秒后隐藏
    setTimeout(() => {
        toast.classList.remove('translate-y-0', 'opacity-100');
        toast.classList.add('translate-y-20', 'opacity-0');
    }, 3000);
}

// 打开购物车侧边栏
function openCartSidebar() {
    cartSidebar.classList.remove('translate-x-full');
    overlay.classList.remove('hidden');
    setTimeout(() => {
        overlay.classList.remove('opacity-0');
        overlay.classList.add('opacity-100');
    }, 10);
    document.body.style.overflow = 'hidden';
}

// 关闭购物车侧边栏
function closeCartSidebar() {
    cartSidebar.classList.add('translate-x-full');
    overlay.classList.remove('opacity-100');
    overlay.classList.add('opacity-0');
    setTimeout(() => {
        overlay.classList.add('hidden');
    }, 300);
    document.body.style.overflow = '';
}

// 更新购物车UI
function updateCartUI() {
    // 更新购物车数量
    const totalItems = cart.reduce((total, item) => total + item.quantity, 0);
    cartCount.textContent = totalItems;
    
    // 更新购物车内容
    if (cart.length === 0) {
        emptyCart.classList.remove('hidden');
        cartItems.classList.add('hidden');
        checkoutBtn.disabled = true;
        checkoutBtn.classList.add('opacity-50', 'cursor-not-allowed');
    } else {
        emptyCart.classList.add('hidden');
        cartItems.classList.remove('hidden');
        checkoutBtn.disabled = false;
        checkoutBtn.classList.remove('opacity-50', 'cursor-not-allowed');
        
        // 渲染购物车项目
        cartItems.innerHTML = '';
        cart.forEach(item => {
            const cartItem = document.createElement('div');
            cartItem.className = 'flex items-center gap-4 pb-4 border-b';
            cartItem.innerHTML = `
                <img src="${item.product.image_url}" alt="${item.product.name}" class="w-16 h-16 object-cover rounded">
                <div class="flex-1 min-w-0">
                    <h4 class="font-medium line-clamp-1">${item.product.name}</h4>
                    <div class="text-sm text-gray-500">${item.product.category}</div>
                    <div class="flex justify-between items-center mt-1">
                        <span class="font-bold text-primary">¥${item.product.price.toFixed(2)}</span>
                        <div class="flex items-center">
                            <button class="cart-decrease qty-btn p-1 text-gray-500 hover:text-primary" data-id="${item.product.id}">
                                <i class="fa fa-minus"></i>
                            </button>
                            <span class="mx-2 w-6 text-center">${item.quantity}</span>
                            <button class="cart-increase qty-btn p-1 text-gray-500 hover:text-primary" data-id="${item.product.id}">
                                <i class="fa fa-plus"></i>
                            </button>
                        </div>
                    </div>
                </div>
                <button class="cart-remove text-gray-400 hover:text-red-500" data-id="${item.product.id}">
                    <i class="fa fa-trash"></i>
                </button>
            `;
            cartItems.appendChild(cartItem);
        });
        
        // 绑定购物车项目事件
        document.querySelectorAll('.cart-decrease').forEach(btn => {
            btn.addEventListener('click', () => {
                const productId = parseInt(btn.dataset.id);
                updateCartItemQuantity(productId, -1);
            });
        });
        
        document.querySelectorAll('.cart-increase').forEach(btn => {
            btn.addEventListener('click', () => {
                const productId = parseInt(btn.dataset.id);
                updateCartItemQuantity(productId, 1);
            });
        });
        
        document.querySelectorAll('.cart-remove').forEach(btn => {
            btn.addEventListener('click', () => {
                const productId = parseInt(btn.dataset.id);
                removeFromCart(productId);
            });
        });
    }
    
    // 更新总计
    const total = cart.reduce((sum, item) => sum + (item.product.price * item.quantity), 0);
    cartTotal.textContent = `¥${total.toFixed(2)}`;
}

// 添加商品到购物车
function addToCart(productId, quantity) {
    const product = products.find(p => p.id === productId);
    if (!product) return;
    
    // 检查商品是否已在购物车中
    const existingItemIndex = cart.findIndex(item => item.product.id === productId);
    
    if (existingItemIndex > -1) {
        // 更新数量
        cart[existingItemIndex].quantity += quantity;
    } else {
        // 添加新商品
        cart.push({ product, quantity });
    }
    
    // 更新UI
    updateCartUI();
    showToast(`已将 ${product.name} 添加到购物车`);
    
    // 如果用户已登录，同步到服务器
    if (accessToken) {
        syncCartToServer();
    } else {
        // 未登录，保存到本地存储
        localStorage.setItem('cart', JSON.stringify(cart));
    }
}

// 更新购物车商品数量
function updateCartItemQuantity(productId, change) {
    const itemIndex = cart.findIndex(item => item.product.id === productId);
    if (itemIndex === -1) return;
    
    const newQuantity = cart[itemIndex].quantity + change;
    
    if (newQuantity <= 0) {
        // 数量为0时移除商品
        removeFromCart(productId);
        return;
    }
    
    // 更新数量
    cart[itemIndex].quantity = newQuantity;
    updateCartUI();
    
    // 同步到服务器或本地存储
    if (accessToken) {
        syncCartToServer();
    } else {
        localStorage.setItem('cart', JSON.stringify(cart));
    }
}

// 从购物车移除商品
function removeFromCart(productId) {
    const item = cart.find(item => item.product.id === productId);
    if (!item) return;
    
    cart = cart.filter(item => item.product.id !== productId);
    updateCartUI();
    showToast(`已从购物车移除 ${item.product.name}`);
    
    // 同步到服务器或本地存储
    if (accessToken) {
        syncCartToServer();
    } else {
        localStorage.setItem('cart', JSON.stringify(cart));
    }
}

// 同步购物车到服务器
async function syncCartToServer() {
    if (!accessToken) return;
    
    try {
        const response = await fetch('http://192.168.10.124:8000/cart/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${accessToken}`
            },
            body: JSON.stringify({
                items: cart.map(item => ({
                    product_id: item.product.id,
                    quantity: item.quantity
                }))
            })
        });
        
        if (!response.ok) throw new Error('Failed to sync cart');
    } catch (error) {
        console.error('Error syncing cart:', error);
        showToast('购物车同步失败', 'error');
    }
}

// 切换移动端菜单
function toggleMobileMenu() {
    mobileMenu.classList.toggle('hidden');
}

// 检查用户认证状态
async function checkAuth() {
    if (accessToken) {
        try {
            const response = await fetch('http://192.168.10.124:8000/auth/user/', {
                headers: { 'Authorization': `Bearer ${accessToken}` }
            });
            
            if (response.ok) {
                const userData = await response.json();
                currentUser = userData;
                updateUserUI();
                
                // 如果本地有购物车数据，合并到服务器
                const localCart = localStorage.getItem('cart');
                if (localCart) {
                    const parsedCart = JSON.parse(localCart);
                    if (parsedCart.length > 0) {
                        // 先加载服务器购物车，再合并本地购物车
                        await loadCart();
                        parsedCart.forEach(item => {
                            addToCart(item.product.id, item.quantity);
                        });
                        localStorage.removeItem('cart'); // 合并后清除本地购物车
                    }
                }
            } else {
                // Token无效或过期
                logout();
            }
        } catch (error) {
            console.error('Error checking auth:', error);
            logout();
        }
    } else {
        // 未登录，从本地存储加载购物车
        const localCart = localStorage.getItem('cart');
        if (localCart) {
            try {
                cart = JSON.parse(localCart);
                updateCartUI();
            } catch (e) {
                console.error('Error parsing local cart:', e);
                localStorage.removeItem('cart');
            }
        }
    }
}

// 更新用户UI（添加调试信息）
function updateUserUI() {
    const adminLink = document.getElementById('adminCreateProduct');
    
    if (currentUser) {
        document.getElementById('auth-links').classList.add('hidden');
        userInfo.classList.remove('hidden');
        userInfo.querySelector('span').textContent = currentUser.username;
        
        // 检查是否为管理员，显示创建商品链接
        if (currentUser.is_admin) {  
            console.log('判断结果：是管理员，显示创建商品链接');
            if (adminLink) adminLink.classList.remove('hidden');
        } else {
            console.log('判断结果：非管理员，隐藏创建商品链接');
            if (adminLink) adminLink.classList.add('hidden');
        }
    } else {
        console.log('判断结果：用户未登录，隐藏创建商品链接');
        document.getElementById('auth-links').classList.remove('hidden');
        userInfo.classList.add('hidden');
        if (adminLink) adminLink.classList.add('hidden');
    }
}

// 登出
function logout() {
    localStorage.removeItem('access_token');
    accessToken = null;
    currentUser = null;
    cart = [];
    updateUserUI();
    updateCartUI();
    showToast('已成功登出');
    window.location.href = 'index.html';
}

// 打开快速查看模态框
function openQuickViewModal(productId) {
    const product = products.find(p => p.id === productId);
    if (!product) return;
    
    currentQuickViewProductId = productId;
    quickViewImage.src = product.image_url;
    quickViewImage.alt = product.name;
    quickViewTitle.textContent = product.name;
    quickViewCategory.textContent = product.category;
    quickViewRating.innerHTML = generateRatingStars(product.rating);
    quickViewReviews.textContent = `${product.reviews}条评价`;
    quickViewPrice.textContent = `¥${product.price.toFixed(2)}`;
    quickViewDescription.textContent = product.description;
    quickViewQty.value = 1;
    quickViewProductLink.href = `product.html?id=${productId}`;
    
    quickViewModal.classList.remove('hidden');
    document.body.style.overflow = 'hidden';
}

// 关闭快速查看模态框
function closeQuickViewModal() {
    quickViewModal.classList.add('hidden');
    document.body.style.overflow = '';
    currentQuickViewProductId = null;
}